# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 10:46:00 2020

@author: Colleen
"""

from tensorflow.keras.models import load_model
import os
import librosa
import numpy as np


def tran_8000(test_dir, test_dir_list):
#转换乘8000hz
    test_dir_wav_list, test_wav, label_list = [],[], []
    for wav in test_dir_list: 
        samples, sample_rate = librosa.load(os.path.join(test_dir, wav))
        samples = librosa.resample(samples, sample_rate, 8000)
        if len(samples) == 8000:
            label = wav.split('_')[0]
            test_wav.append(samples)
            label_list.append(label)
            test_dir_wav_list.append(wav)
    return test_wav, label_list, test_dir_wav_list

model = load_model('my_model.h5', compile = False)
label =['yes', 'no', 'up', 'down', 'left', 'right', 'on', 'off', 'stop', 'go', 'unknown', 'silence']
order = ['yes', 'no', 'up', 'down', 'left', 'right', 'on', 'off', 'stop', 'go']
test = 'data\\test_shengxia'
sum_num = 0
right_num = 0
for test_name in os.listdir(test):
    test_dir = os.path.join(test,test_name)
    test_dir_list = os.listdir(test_dir)#1499
    
    test_wav, label_list, test_dir_wav_list = tran_8000(test_dir, test_dir_list)
    
    test_wav_ar = np.reshape(test_wav, (-1, 8000)) 
    test_wav_arr2 = test_wav_ar.reshape(-1,8000,1)
    #print(len(test_wav), len(label_list))
      
    
    pre_resu = model.predict(test_wav_arr2)
    
    pre_label_list = []
    for la in pre_resu:
        num = np.argmax(la)
       # print(num)
        pre_label_list.append(label[num])
    
    if test_name not in label:
        test_name = 'unknown'
   
    sum_num = sum_num + len(test_wav_arr2)
    right_num = pre_label_list.count(test_name)+ right_num

acc = right_num/sum_num